from daemon import Daemon
import sys, os
import inotifyx
from parser import parse
from config import *

def auinit():
    os.popen('auditctl -D').read()
    os.popen('auditctl -w /usr/bin/sudo -p x -k %s' % SUDO_KEY).read()
    for w in WATCH:
        os.popen('auditctl -w %s -p wa -k %s' % (w, KEY)).read()

class Attrustd(Daemon):
    def run(self):
        f = open(ATTRUST_LOG, 'w')
        min_id = 0
        ts = 0
        fd = inotifyx.init()
        inotifyx.add_watch(fd, AUDIT_LOG, inotifyx.IN_MODIFY)
        while True:
            inotifyx.get_events(fd)
            records = parse(KEY, sudo_key=SUDO_KEY, min_id=min_id, ts=ts)
            if not records:
                continue
            for r in records:
                f.write('%s\n' % str(r))
                f.flush()
            min_id = records[-1]['id']
            ts = records[-1]['ts']

if __name__ == '__main__':
    auinit()
    attrustd = Attrustd('/tmp/attrustd.pid')
    if len(sys.argv) == 2:
        try:
            getattr(attrustd, sys.argv[1])()
        except AttributeError:
            print 'Unknown commands'
    else:
        print 'Usage: attrustd start|stop|restart'
